package com.wzu.service;

import com.wzu.dao.UserDao;
import com.wzu.dao.UserDaoImpl;
import com.wzu.dao.ReaderDao;
import com.wzu.dao.ReaderDaoImpl;
import com.wzu.pojo.User;
import com.wzu.pojo.Reader;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    private ReaderDao readerDao = new ReaderDaoImpl();  // ✅ 添加 ReaderDao

    @Override
    public User login(String username, String password) {
        User user = userDao.findUserByUsernameAndPassword(username, password);
        if (user != null) {
            String hashedPassword = hashPassword(password);
            if (hashedPassword != null && hashedPassword.equals(user.getPassword())) {
                return user;
            }
        }
        return null;
    }

    @Override
    public boolean register(User user) {
        return userDao.registerUser(user) > 0;
    }


    @Override
    public boolean updatePassword(int userId, String newPassword) {
        String hashedPassword = hashPassword(newPassword);
        if (hashedPassword == null) {
            return false;
        }
        int rows = userDao.updatePassword(userId, hashedPassword);
        return rows > 0;
    }

    // ✅ 实现 registerReader 方法
    @Override
    public boolean registerReader(Reader reader) {
        return readerDao.insertReader(reader) > 0;
    }
    @Override
    public User getUserByUsername(String username) {
        return userDao.findUserByUsername(username);
    }

    // 密码加密方法
    private String hashPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(password.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}
